package com.one.common.security.interceptor;

import cn.hutool.core.util.StrUtil;
import com.one.common.core.constants.Constants;
import com.one.common.core.constants.HttpConstants;
import com.one.common.core.util.ThreadLocalUtil;
import com.one.common.security.service.TokenService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@RefreshScope
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    //从哪个服务的配置文件中获取，取决于这个bean对象交给了哪个服务的spring容器管理
    @Value("${jwt.secret}")
    private String secret;

    // 那个服务用到了拦截器，这个拦截器就注入到那个服务的Spring容器当中
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //在这里延长token时间
        //先获取到token
        String token = getToken(request);
        if(token == null){
            return true;
        }
        Long userId = Long.valueOf(tokenService.getUserId(token, secret));
        String userKey = tokenService.getUserKey(token, secret);
        ThreadLocalUtil.set(Constants.USER_ID,userId);
        ThreadLocalUtil.set(Constants.USER_KEY,userKey);
        tokenService.expireToken(token,secret);
        return true;
    }
    

    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(HttpConstants.AUTHENTICATION);
        // 如果前端设置了令牌前缀，则裁剪掉前缀
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, StrUtil.EMPTY);
        }
        return token;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
